package com.wzapp.sitposture.common.util;

import com.wzapp.sitposture.common.constant.CommonConst;
import com.wzapp.sitposture.common.page.CommonPage;
import com.wzapp.sitposture.common.page.PageParam;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

public class PageUtil {

    /**
     * 功能: 初始化分页参数 <br/>
     *
     * @author ql
     * @date 2018-01-19 13:01
     * @param pageParam
     * @return PageParam
     */
    public static PageParam initPageParam(PageParam pageParam){

        if (ToolUtil.isEmpty(pageParam)) {
            pageParam = new PageParam();
        }

        if (ToolUtil.isEmpty(pageParam.getPageNum())) {
            pageParam.setPageNum(CommonConst.DEFAULT_PAGE_START);
        }

        if (ToolUtil.isEmpty(pageParam.getPageSize()) || pageParam.getPageSize() > 50) {
            pageParam.setPageSize(CommonConst.DEFAULT_PAGE_SIZE);
        }

        return pageParam;
    }

    public static Pageable convertToPageable(PageParam pageParam) {
        initPageParam(pageParam);

        Pageable pageable = new PageRequest(pageParam.getPageNum(), pageParam.getPageSize());

        return pageable;
    }

    public static Pageable convertToPageable(PageParam pageParam, Sort sort) {
        initPageParam(pageParam);

        Pageable pageable = new PageRequest(pageParam.getPageNum(), pageParam.getPageSize(), sort);

        return pageable;
    }

    public static <R> CommonPage<R> copyFrameworkToEigpage(Page page) {
        CommonPage<R> result = new CommonPage();

        result.setFirst(page.isFirst());
        result.setLast(page.isLast());
        result.setNumber(page.getNumber());
        result.setNumberOfElements(page.getNumberOfElements());
        result.setSize(page.getSize());
        result.setTotalElements(page.getTotalElements());
        result.setTotalPages(page.getTotalPages());
        result.setSort(page.getSort());

        return result;
    }
}
